<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;
use aphp\core\Tool;

class Md
{
    use Jump;

    protected function _check_level(int $level = 1)
    {
        if ((int)session('user.level') < $level) {
            $this->error('权限不足', 403);
        }
    }

    // 查看
    public function index(int $id)
    {
        $vo = widget('doc_data')->get($id);
        if (!$vo) {
            $this->error('此文档暂无内容');
        }
        return view()->with(['vo' => $vo, 'doc_id' => $vo['doc_id']]);
    }

    // 下载
    public function down(int $id)
    {
        $vo = widget('doc_data')->get($id);
        if (!$vo) {
            $this->error('此文档不存在');
        }
        $k = $vo['sort_i'];
        if ($k == 0) {
            $list = db('doc_data')->where('doc_id', $vo['doc_id'])->where('status=1')->order('sort ASC,id ASC')->column('id');
            $k = array_search($id, $list) + 1;
        }
        $k = str_pad(strval($k), 2, '0', STR_PAD_LEFT);
        $file = 'doc/'.$vo['doc_id'].'/_'.$k.'_'.$vo['name'].'.md';
        $path = ROOT_PATH.'/public/'.$file;
        Tool::dir_init(dirname($path));
        file_put_contents($path, $vo['markdown']);
        $this->_url(__URL__.'/'.$file);
    }

    // 新增
    public function add(int $doc_id, array $req)
    {
        $this->_check_level(2);
        if ($this->isPost()) {
            $r = pdo()->trans(function () use ($req) {
                model('doc_data')->save($req);
            });
            $this->_jump(['添加成功', '添加失败'], $r, 'md/index?id='.get_start_id($doc_id));
        }
        return view()->with('doc_id', $doc_id);
    }

    // 修改
    public function edit(int $id, array $req)
    {
        $this->_check_level(2);
        $model = model('doc_data')->find($id);
        if (!$model) {
            $this->error('记录不存在');
        }
        if ($this->isPost()) {
            $r = pdo()->trans(function () use ($model, $req) {
                $model->save($req);
            });
            $this->_jump(['修改成功', '修改失败'], $r, 'md/index?id='.$id);
        }
        return view()->with(['vo' => $model->toArray(), 'doc_id' => $model->doc_id]);
    }

    // 删除
    public function del(int $id)
    {
        $this->_check_level(2);
        if ($this->isAjax()) {
            $model = model('doc_data')->find($id);
            if (!$model) {
                $this->error('记录不存在');
            }
            $doc_id = $model->doc_id;
            $r = $model->del();
            $this->_jump(['删除成功', '删除失败'], $r, 'md/index?id='.get_start_id($doc_id));
        }
        $this->error('非法操作');
    }
}